package simpleauth

import java.io.File;

import java.security.cert.X509Certificate;

import org.apache.commons.httpclient.protocol.Protocol;
import org.springframework.context.support.ClassPathXmlApplicationContext;


import uk.ac.soton.ecs.iam.grid.comms.client.AxisTransport;
import uk.ac.soton.ecs.iam.grid.comms.client.RemoteDataService;
import uk.ac.soton.itinnovation.grid.client.engine.impl.DefaultInvocationEngine;
import uk.ac.soton.itinnovation.grid.client.plugins.GridClientPluginManager;
import uk.ac.soton.itinnovation.grid.client.proxy.HelperProxyFactory;
import uk.ac.soton.itinnovation.grid.client.proxy.InvocationEngineProxyFactory;
import uk.ac.soton.itinnovation.grid.client.proxy.ServiceFactory;
import uk.ac.soton.itinnovation.grid.comms.client.ITInnovSocketFactory;
import uk.ac.soton.itinnovation.grid.comms.client.WSDLCacheImpl;
import uk.ac.soton.itinnovation.grid.comms.client.CertificateFileTrustValidator;
import uk.ac.soton.itinnovation.grid.utils.Identity;
import uk.ac.soton.itinnovation.grid.utils.IdentityProvider;
import uk.ac.soton.itinnovation.grid.utils.KeystoreIdentityProvider;
import uk.ac.soton.itinnovation.grid.utils.UsernameIdentityProvider;


class SimpleUserController {

    def login = { }
    
    def doLogin = {
		IdentityProvider userIdp;				
		def user = User.findWhere(userName:params['userName'], password:params['password'])
		session.user = user
		if (user)
		{
			if (user.keystoreLocation == null)
			{
				String ksDir = grailsApplication.config.gria.identity.keyStoreDir
				user.keystoreLocation = ksDir + user.userName + ".ks";
				user.save();
			}
			File keystoreFile = new File(user.keystoreLocation);
			if (!keystoreFile.exists()) {
				println "Creating Keystore..."
				KeystoreIdentityProvider issuerIdp = new KeystoreIdentityProvider(
						grailsApplication.config.gria.identity.issuerKeystore, grailsApplication.config.gria.identity.issuerPassword.toCharArray());
				Identity issuerId = issuerIdp.getIdentity();
				userIdp = new UsernameIdentityProvider(user.email, grailsApplication.config.gria.identity.dnDomain,
						user.email, user.password, issuerId.getPrivateKey(),
						issuerId.getCertificate());
				Identity id = userIdp.getIdentity(); 
				id = userIdp.getIdentity()
				println id			
				id.saveKeyStore(keystoreFile)	
		    } 
			else {
				println "Existing Keystore found..."
				userIdp = new KeystoreIdentityProvider(user.keystoreLocation,
						user.password.toCharArray());	
				Identity id = userIdp.getIdentity(); 
				id = userIdp.getIdentity()
				println id
				}
			
			println "Creating serviceFactory..."
			
			AxisTransport myTransport = new AxisTransport(userIdp);
			
			myTransport.setCertificateTrustValidator(new CertificateFileTrustValidator(new File(grailsApplication.config.gria.identity.trustCertificateDir)));
			
			WSDLCacheImpl myWsdlCache = new WSDLCacheImpl(myTransport);
			InvocationEngineProxyFactory pf = new InvocationEngineProxyFactory(new DefaultInvocationEngine(myTransport), myWsdlCache);

			GridClientPluginManager gcpm = new GridClientPluginManager();
			gcpm.loadPlugins();
			
			user.helperProxyFactory = new HelperProxyFactory(pf,gcpm.getHelperRegistry());
			
			user.serviceFactory = new ServiceFactory(myWsdlCache, user.helperProxyFactory);	
			
			user.subjectDN = userIdp.getIdentity().getCertificate().getSubjectDN().toString();
			
			print user.subjectDN
			
			if ( flash['from'] != null )
				redirect(controller:flash['from'],action:'list')
			else
				redirect(controller:'job',action:'list')
		}
		else
		{
			flash['from'] = flash['from']
			redirect(controller:'user',action:'login')
		}
	}
}
